package com.monkeyboy.rabbitmq.advanced_features.return_;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ReturnListener;
import com.rabbitmq.client.AMQP.BasicProperties;

public class Producer {
	/**
	 * 作用： Return Listener
	 * 
	 * @Author:Gavin
	 * @time:2018年10月30日
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("localhost");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/myproject");
		connectionFactory.setUsername("Gavin");
		connectionFactory.setPassword("123456");
		// 2.获取到连接对象Connection
		Connection connection = connectionFactory.newConnection();

		// 3.通过Connection创建一个新的Channel
		Channel channel = connection.createChannel();

		// 4.制定我们的消息投递模式：消息的确认模式
		channel.confirmSelect();

		String exchangeName = "test_return_exchange";
		String routingKey = "return.save";
		String routingKeyError = "error.save";

		// 发送一条消息
		/**
		 * Mandatory:需要进行消息不可达的监听， 如果消息不可达就会把该消息进行返回， 不可达的因素：路由key找不到，等
		 * Mandatory如果为false时候：消息没有路由到就会自动删除，
		 * 如果为true时候，没有路由到就不会删除
		 */
		// 添加return的监听
		channel.addReturnListener(new ReturnListener() {
			/**
			 * { replyCode:返回消息码， replyText:返回消息体， routingKey:返回消息路由键, }
			 */
			@Override
			public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
					AMQP.BasicProperties properties, byte[] body) throws IOException {
				System.err.println("-----handle return-----");
				System.err.println("replyCode:" + replyCode);
				System.err.println("replyText:" + replyText);
				System.err.println("exchange:" + exchange);
				System.err.println("routingKey:" + routingKey);
				System.err.println("properties:" + properties);
				System.err.println("body:" + new String(body));

			}
		});
		// 发送成功路由的消息
		//channel.basicPublish(exchangeName, routingKey, true, null, "Hello return msg".getBytes());
		//发送失败路由的消息
		channel.basicPublish(exchangeName, routingKeyError, true, null, "Hello return msg".getBytes());
		/**
		 * Mandatory为false不会进行监听
		 */
		//channel.basicPublish(exchangeName, routingKeyError, false, null, "Hello return msg".getBytes());
		// 关闭通道和连接
		// channel.close();
		// connection.close();
	}
}
